import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  ModalForm,
  ProForm,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Form } from 'antd';
import { useRef, useState } from 'react';
import {
  createDist,
  deleteDist,
  listDists,
  updateDist,
} from '@/services/sys/dict/api';

const columns: ProColumns<DistTypes.List>[] = [
  {
    title: '字典类型编码',
    dataIndex: 'typeCode',
  },
  {
    title: '字典项编码',
    dataIndex: 'code',
  },
  {
    title: '字典项名称',
    dataIndex: 'name',
  },
  {
    title: '父级字典项编码',
    dataIndex: 'parentCode',
  },
  {
    title: '排序号',
    dataIndex: 'sortOrder',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    valueEnum: {
      0: {
        text: '禁用',
      },
      1: {
        text: '启用',
      },
    },
    formItemProps: {
      getValueProps: (value) => ({
        value:
          value !== undefined && value !== null ? value.toString() : undefined,
      }),
      getValueFromEvent: (value) => (value ? Number(value) : undefined),
    },
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    render: (_text, record, _, action) => [
      <a
        key="editable"
        onClick={() => {
          action?.startEditable?.(record.id);
        }}
      >
        编辑
      </a>,
    ],
  },
];

const CreateUserForm = ({
  open,
  onCancel,
  onRefresh,
}: {
  open: boolean;
  onCancel: () => void;
  onRefresh: () => void;
}) => {
  const [form] = Form.useForm();
  // 重置表单
  const resetForm = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <ModalForm<DistTypes.Create>
      title="新建字典"
      form={form}
      open={open}
      autoFocusFirstInput
      modalProps={{
        destroyOnHidden: true,
        onCancel: () => {
          console.log('取消新建');
          resetForm();
        },
      }}
      onFinish={async (values) => {
        createDist(values);
        resetForm();
        onRefresh();
      }}
    >
      <ProForm.Group>
        <ProFormText width="md" name="typeCode" label="字典类型编码" />
        <ProFormText width="md" name="code" label="字典项编码" />
        <ProFormText width="md" name="name" label="字典项名称" />
        <ProFormText width="md" name="parentCode" label="父级字典项编码" />
        <ProFormText width="md" name="sortOrder" label="排序号" />
        <ProFormText width="md" name="remark" label="备注" />
      </ProForm.Group>
    </ModalForm>
  );
};

export default () => {
  const actionRef = useRef<ActionType>(null);
  const [formVisible, setFormVisible] = useState(false);
  const handleOpenForm = () => setFormVisible(true);
  const handleCloseForm = () => setFormVisible(false);
  return (
    <ProTable<DistTypes.List>
      columns={columns}
      actionRef={actionRef}
      cardBordered
      // 获取列表
      request={async (params, _sort, _filter) => {
        const msg = await listDists({
          ...params,
          pageNum: params.current,
        });
        return {
          data: msg.list,
          success: true,
          total: msg.total,
        };
      }}
      // 编辑列表
      editable={{
        type: 'multiple',
        onSave: async (_key, record, _originRow) => {
          const updateParam = record as DistTypes.Update;

          updateDist(updateParam);
          actionRef.current?.reload();
        },
        onDelete: async (_key, row) => {
          deleteDist(row.id);
          actionRef.current?.reload();
        },
      }}
      // 列设置
      columnsState={{
        persistenceKey: 'pro-table-singe-demos',
        persistenceType: 'localStorage',
        defaultValue: {
          option: { fixed: 'right', disable: true },
        },
        onChange(value) {
          console.log('value: ', value);
        },
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      options={{
        setting: {
          listsHeight: 400,
        },
      }}
      form={{
        // 由于配置了 transform，提交的参数与定义的不同这里需要转化一下
        syncToUrl: (values, type) => {
          if (type === 'get') {
            return {
              ...values,
              created_at: [values.startTime, values.endTime],
            };
          }
          return values;
        },
      }}
      pagination={{
        pageSize: 5,
        onChange: (page) => console.log(page),
      }}
      dateFormatter="string"
      headerTitle="字典管理"
      toolBarRender={() => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => handleOpenForm()}
          type="primary"
        >
          新建
        </Button>,
        <CreateUserForm
          key="create-form"
          open={formVisible}
          onCancel={handleCloseForm}
          onRefresh={() => actionRef.current?.reload()}
        />,
      ]}
    />
  );
};
